<?php

namespace app\admin\model;

use think\Model;
use think\Db;
use traits\model\SoftDelete;

class Order extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function listAll(){
        echo json_encode(Order::field('id,name,tel,address,brand,oid,cid,date,price')->select(), JSON_UNESCAPED_UNICODE);
    }

    public function saveDate($data)
    {
        $result = $this->validate(true)->allowField(true)->save($data);
        if(false === $result){
            $error = $this->getError();
            return array('code'=>0,'msg'=>$error);
        }else{
            return 'success';
        }
    }

    public function deleteById($id)
    {
        $result = Order::destroy($id);
        if ($result > 0) {
            return array('code'=>1,'msg'=>'删除成功');
        }
    }

    public function edit(array $data = [])
    {
        $result = $this->validate(true)->allowField(true)->save($data,['id'=>$data['id']]);
        if(false === $result){
            $error = $this->getError();
            return array('code'=>0,'msg'=>$error);
        }else{
            return 'success';
        }
    }

    public function chartLine(){
        $count = $this->field('date,count(id) AS value')
            ->where('date','between','2016-11-04,2016-11-22')
            ->group('date')
            ->select()
            ->toArray();
        $data1 = array_column($count, 'date');
        $data2 = array_column($count, 'value');

        foreach ($data1 as $key => $val) {
            $o_data[$key]['kind'] = '订单';
            $o_data[$key]['date'] = $data1[$key];
            $o_data[$key]['value'] = $data2[$key];
        }
        return $o_data;
    }

    public function countId(){
        $count = $this->field('tp_brand.brand,count(o.id) AS num')
            ->alias('o')
            ->join('tp_brand','tp_brand.brand = o.brand','right')
            ->group('tp_brand.brand')
            ->order('convert(tp_brand.brand using gbk) asc')
            ->select()
            ->toArray();
        return $count;
    }

    public function dateCount($date){
        $count = Db::query("SELECT
tp_brand.brand,
Count(tp_order.id) AS num
FROM
tp_brand
LEFT JOIN tp_order ON tp_brand.brand = tp_order.brand AND tp_order.date = '$date'
WHERE tp_order.delete_time IS NULL
GROUP BY
tp_brand.brand
ORDER BY
CONVERT (tp_brand.brand USING gbk) ASC");
        return $count;
    }
}
